package com.ugoodtech.mdcc.core.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;

import java.io.*;

//org/apache/http/ssl/TrustStrategy

public class AliServiceUtil {
    //    @Value("${oss.bucketName}")
//    public static final String bucketName = "spc-bucket";
//    public static final String bucketName = "cere-test";
//
    // 目前只有"cn-hangzhou"这个region可用, 不要使用填写其他region的值
    public static final String REGION_CN_HANGZHOU = "cn-hangzhou";
    // 当前 STS API 版本
    public static final String STS_API_VERSION = "2015-04-01";

    //    @Value("${oss.accessKeyId}")
//    public static final String ACCESS_KEY_ID = "LTAI1961lyKjwiQm";
    public static final String ACCESS_KEY_ID = "LTAISmTXUDxswBvH";

    //    @Value("${oss.accessKeySecret}")
//    public static final String ACCESS_KEY_SECRET = "XCOLMSLm6a2D01ehGA7Qbno2nkjbYk";
    public static final String ACCESS_KEY_SECRET = "41DyY1gzJPI0Z9lejCmvZYs0eu73yo";
    //    @Value("${oss.endpoint}")
//    public static final String ENDPOINT = "http://oss-cn-hongkong.aliyuncs.com/";
    public static final String ENDPOINT = "http://oss-cn-hangzhou.aliyuncs.com/";

//    public static final String REGION_CN_HANGZHOU = "cn-hangzhou";
//    // 当前 STS API 版本
//    public static final String STS_API_VERSION = "2015-04-01";
//
//    //    @Value("${oss.accessKeyId}")
//    public static final String ACCESS_KEY_ID = "LTAI5aZfiqNFD2ED";
//    //    @Value("${oss.accessKeySecret}")
//    public static final String ACCESS_KEY_SECRET = "VnERqvBMgso2vHDdsDYm03zBuxTVqS";
//    //    @Value("${oss.endpoint}")
//    public static final String ENDPOINT = "http://oss-cn-shanghai.aliyuncs.com/";

    public static final String ROLE_ARN = "acs:ram::1870537971533227:role/aliyunosstokengeneratorrole";
    public static final String POLICY = "{\n" +
            "    \"Version\": \"1\", \n" +
            "    \"Statement\": [\n" +
            "        {\n" +
            "            \"Action\": [\n" +
            "                \"oss:Get*\", \n" +
//                "                \"oss:GetBucket\", \n" +
//                "                \"oss:GetObject\", \n" +
            "                \"oss:Put*\" \n" +
//                "                \"oss:PutObject\" \n" +
            "            ], \n" +
            "            \"Resource\": [\n" +
            "                \"acs:oss:*:*:*\"\n" +
            "            ], \n" +
            "            \"Effect\": \"Allow\"\n" +
            "        }\n" +
            "    ]\n" +
            "}";

    //生成STS临时令牌
    public static AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret,
                                                String roleArn, String roleSessionName, String policy) throws ClientException {
        try {
            // 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
            IClientProfile profile = DefaultProfile.getProfile(REGION_CN_HANGZHOU, accessKeyId, accessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            // 创建一个 AssumeRoleRequest 并设置请求参数
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setVersion(STS_API_VERSION);
            request.setMethod(MethodType.POST);
            request.setProtocol(ProtocolType.HTTPS);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(policy);
            request.setDurationSeconds(Long.valueOf("3600"));
            // 发起请求，并得到response
            AssumeRoleResponse response = client.getAcsResponse(request);
            return response;
        } catch (ClientException e) {
            throw e;
        }
    }

    public static InputStream getObject(String photoId, String bucketName) throws IOException {
        // 创建OSSClient实例
        OSSClient client = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        // 使用访问OSS

        OSSObject object = client.getObject(bucketName, photoId);

        InputStream returnStream = copyInputstream(object.getObjectContent());
        // 关闭client
        client.shutdown();

        return returnStream;
    }


    public static void downLoad(String photoId, String bucketName, String filePath) {
        OSSClient ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
        ossClient.getObject(new GetObjectRequest(bucketName, photoId), new File(filePath));

        // 关闭OSSClient。
        ossClient.shutdown();
    }

    public static void putObject(InputStream in, String dir, String bucketName) throws IOException {
        OSSClient client = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        // 使用访问OSS

        client.putObject(bucketName, dir, in);

        // 关闭client
        client.shutdown();
    }

    public static void putFile(File file, String dir, String bucketName) throws IOException {
        OSSClient client = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        // 使用访问OSS

        client.putObject(bucketName, dir, file);

        // 关闭client
        client.shutdown();
    }

    public static void downloadFolderFile(String prefix, String filename, String bucketName) throws IOException {
        OSSClient client = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        // 列出fun目录下的所有文件和文件夹
//        String prefix = "data/attachment/customerpic/-10039/";
        (new File(filename + prefix)).mkdirs();

        downloadFolderFile(client, prefix, filename, bucketName);
        // 关闭client
        client.shutdown();
    }

    private static void downloadFolderFile(OSSClient client, String prefix, String filename, String bucketName) throws IOException {
        // 构造ListObjectsRequest请求
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
        // "/" 为文件夹的分隔符
        listObjectsRequest.setDelimiter("/");
        // 列出fun目录下的所有文件和文件夹
        listObjectsRequest.setPrefix(prefix);
        ObjectListing listing = client.listObjects(listObjectsRequest);
        // 遍历所有Object
        System.out.println("Objects:");
        for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
            System.out.println(objectSummary.getKey());
            client.getObject(new GetObjectRequest(bucketName, objectSummary.getKey()), new File(filename + "/" + objectSummary.getKey()));
        }
        // 遍历所有CommonPrefix
        System.out.println("\nCommonPrefixs:");
        for (String commonPrefix : listing.getCommonPrefixes()) {
            System.out.println(commonPrefix);
            (new File(filename + "/" + commonPrefix)).mkdirs();
            downloadFolderFile(client, commonPrefix, filename, bucketName);
        }
    }
//    public static InputStream getObject(String photoId, AssumeRoleResponse response) throws IOException {
//        // 只有 RAM用户（子账号）才能调用 AssumeRole 接口
//        // 阿里云主账号的AccessKeys不能用于发起AssumeRole请求
//        // 请首先在RAM控制台创建一个RAM用户，并为这个用户创建AccessKeys
//        System.out.println("Expiration: " + response.getCredentials().getExpiration());
//        System.out.println("Access Key Id: " + response.getCredentials().getAccessKeyId());
//        System.out.println("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
//        System.out.println("Security Token: " + response.getCredentials().getSecurityToken());
//
//        String accessKeyIdTmp = response.getCredentials().getAccessKeyId();
//        String accessKeySecretTmp = response.getCredentials().getAccessKeySecret();
//        String securityTokenTmp = response.getCredentials().getSecurityToken();
//        // 创建ClientConfiguration实例，按照您的需要修改默认参数
//        ClientConfiguration conf = new ClientConfiguration();
//        // 开启支持CNAME选项
//        conf.setSupportCname(true);
//        // 创建OSSClient实例
//        OSSClient client = new OSSClient(ENDPOINT, accessKeyIdTmp, accessKeySecretTmp, securityTokenTmp);
//        // 使用访问OSS
//
//        OSSObject object = client.getObject(bucketName, photoId);
//
//        InputStream returnStream = copyInputstream(object.getObjectContent());
//        // 关闭client
//        client.shutdown();
//
//        return returnStream;
//    }

//    public static void putObject(InputStream in, AssumeRoleResponse response, String dir) throws IOException {
//        System.out.println("Expiration: " + response.getCredentials().getExpiration());
//        System.out.println("Access Key Id: " + response.getCredentials().getAccessKeyId());
//        System.out.println("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
//        System.out.println("Security Token: " + response.getCredentials().getSecurityToken());
//        System.out.println("dirn: " + dir);
//
//        String accessKeyIdTmp = response.getCredentials().getAccessKeyId();
//        String accessKeySecretTmp = response.getCredentials().getAccessKeySecret();
//        String securityTokenTmp = response.getCredentials().getSecurityToken();
//        System.out.println("===========1===========");
//        // 创建ClientConfiguration实例，按照您的需要修改默认参数
//        ClientConfiguration conf = new ClientConfiguration();
//        System.out.println("===========2===========");
//        // 开启支持CNAME选项
//        conf.setSupportCname(true);
//        conf.setSLDEnabled(true);
//        System.out.println("===========3===========");
//        // 创建OSSClient实例
////            OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
//        OSSClient client = new OSSClient(ENDPOINT, accessKeyIdTmp, accessKeySecretTmp, securityTokenTmp, conf);
//        System.out.println("===========4===========");
//        // 使用访问OSS
//
//        client.putObject(bucketName, dir, in);
//        System.out.println("===========5===========");
//
//        // 关闭client
//        client.shutdown();
//        System.out.println("===========6===========");
//    }

    public static boolean doesObjectExist(String photoId, String bucketName) throws IOException {
        OSSClient client = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        // 使用访问OSS
        boolean doesExist = client.doesObjectExist(bucketName, photoId);

        // 关闭client
        client.shutdown();

        return doesExist;
    }

    public static void putObject(OSSClient client, String photoId, InputStream in, String bucketName) throws IOException {
        client.putObject(bucketName, photoId, in);
    }

//    public static void main(String[] args) throws FileNotFoundException {
//        // 只有 RAM用户（子账号）才能调用 AssumeRole 接口
//        // 阿里云主账号的AccessKeys不能用于发起AssumeRole请求
//        // 请首先在RAM控制台创建一个RAM用户，并为这个用户创建AccessKeys
//        String accessKeyId = "UqK9K2brci2KmDZ1";
//        String accessKeySecret = "U2A0l0OYfcUzq6ZCetXneqPOv89GlA";
//        // AssumeRole API 请求参数: RoleArn, RoleSessionName, Policy, and DurationSeconds
//        // RoleArn 需要在 RAM 控制台上获取
//        String roleArn = "acs:ram::1870537971533227:role/aliyunosstokengeneratorrole";
//        // RoleSessionName 是临时Token的会话名称，自己指定用于标识你的用户，主要用于审计，或者用于区分Token颁发给谁
//        // 但是注意RoleSessionName的长度和规则，不要有空格，只能有'-' '_' 字母和数字等字符
//        // 具体规则请参考API文档中的格式要求
//        String roleSessionName = "alice-001";
//        // 如何定制你的policy?
//        String policy = "{\n" +
//                "    \"Version\": \"1\", \n" +
//                "    \"Statement\": [\n" +
//                "        {\n" +
//                "            \"Action\": [\n" +
//                "                \"oss:Get*\", \n" +
////                "                \"oss:GetBucket\", \n" +
////                "                \"oss:GetObject\", \n" +
//                "                \"oss:Put*\" \n" +
////                "                \"oss:PutObject\" \n" +
//                "            ], \n" +
//                "            \"Resource\": [\n" +
//                "                \"acs:oss:*:*:*\"\n" +
//                "            ], \n" +
//                "            \"Effect\": \"Allow\"\n" +
//                "        }\n" +
//                "    ]\n" +
//                "}";
//        // 此处必须为 HTTPS
//        ProtocolType protocolType = ProtocolType.HTTPS;
//        try {
//            final AssumeRoleResponse response = assumeRole(accessKeyId, accessKeySecret,
//                    roleArn, roleSessionName, policy, protocolType);
//            System.out.println("Expiration: " + response.getCredentials().getExpiration());
//            System.out.println("Access Key Id: " + response.getCredentials().getAccessKeyId());
//            System.out.println("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
//            System.out.println("Security Token: " + response.getCredentials().getSecurityToken());
//
//            String endpoint = "oss-cn-shanghai.aliyuncs.com";
//            String accessKeyIdTmp = response.getCredentials().getAccessKeyId();
//            String accessKeySecretTmp = response.getCredentials().getAccessKeySecret();
//            String securityTokenTmp = response.getCredentials().getSecurityToken();
//            // 创建ClientConfiguration实例，按照您的需要修改默认参数
//            ClientConfiguration conf = new ClientConfiguration();
//            // 开启支持CNAME选项
//            conf.setSupportCname(true);
//            // 创建OSSClient实例
////            OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
//            OSSClient client = new OSSClient(endpoint, accessKeyIdTmp, accessKeySecretTmp, securityTokenTmp);
//            // 使用访问OSS
//
//            File file = new File("E://Cesc.jpg");
//            InputStream in = new FileInputStream(file);
//            client.putObject("meice", "test.jpg", in);
//            System.out.println("Object：" + "test.jpg" + "存入OSS成功。");
//
//
//            // 关闭client
//            client.shutdown();
//
//
//
//        } catch (ClientException e) {
//            System.out.println("Failed to get a token.");
//            System.out.println("Error code: " + e.getErrCode());
//            System.out.println("Error message: " + e.getErrMsg());
//        }
////        String endpoint = "oss-cn-shanghai.aliyuncs.com";
////        OSSClient client = new OSSClient(endpoint, "STS.McZK8ck8JjzKMKy8GKF88nb93", "A3yRZV3YmtcfnY2H1xdut3TtYXpUdjPwLvShNDATudjw", "CAESoQMIARKAAVz2knrWpf+sKWI/aG8C0O0aAVo3M19r3mp3havnKtBmgGOxe/ZqGInASWw5exsx/rK+EeMaRO0AB4IYNTRgdo/W0cKBNLHfKOi/yAvmvGUQsdghYTUY7TvElJY0HnXD9hSjsjZ9Dt4miee5mqVh7pSzoDGv8B8wATdY5pZ5KlFWGh1TVFMuTWNaSzhjazhKanpLTUt5OEdLRjg4bmI5MyISMzU3NDk2NTY3NzA5MjAwNzUwKglhbGljZS0wMDEwvf7AodwqOgZSc2FNRDVCZwoBMRpiCgVBbGxvdxIsCgxBY3Rpb25FcXVhbHMSBkFjdGlvbhoUCghvc3M6R2V0KgoIb3NzOlB1dCoSKwoOUmVzb3VyY2VFcXVhbHMSCFJlc291cmNlGg8KDWFjczpvc3M6KjoqOipKEDE4NzA1Mzc5NzE1MzMyMjdSBTI2ODQyWg9Bc3N1bWVkUm9sZVVzZXJgAGoSMzU3NDk2NTY3NzA5MjAwNzUwchthbGl5dW5vc3N0b2tlbmdlbmVyYXRvcnJvbGV4q4vU+uinqQM=");
////                    File file = new File("E://Cesc.jpg");
////            InputStream in = new FileInputStream(file);
////            client.putObject("meice", "test.jpg", in);
////            System.out.println("Object：" + "test.jpg" + "存入OSS成功。");
////        client.shutdown();
//    }

    public static OSSClient openOSSClient(AssumeRoleResponse response) {
        // 只有 RAM用户（子账号）才能调用 AssumeRole 接口
        // 阿里云主账号的AccessKeys不能用于发起AssumeRole请求
        // 请首先在RAM控制台创建一个RAM用户，并为这个用户创建AccessKeys
        System.out.println("Expiration: " + response.getCredentials().getExpiration());
        System.out.println("Access Key Id: " + response.getCredentials().getAccessKeyId());
        System.out.println("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
        System.out.println("Security Token: " + response.getCredentials().getSecurityToken());

        String accessKeyIdTmp = response.getCredentials().getAccessKeyId();
        String accessKeySecretTmp = response.getCredentials().getAccessKeySecret();
        String securityTokenTmp = response.getCredentials().getSecurityToken();
        // 创建OSSClient实例
        return new OSSClient(ENDPOINT, accessKeyIdTmp, accessKeySecretTmp, securityTokenTmp);
    }

    public static void closeOSSClient(OSSClient client) {
        client.shutdown();
    }

    private static InputStream copyInputstream(InputStream input) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[10240];
        int len;
        while ((len = input.read(buffer)) > -1) {
            baos.write(buffer, 0, len);
        }
        baos.flush();
        input.close();
        return new ByteArrayInputStream(baos.toByteArray());
    }
}